package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @ClassNameUserServiceImpl
 * @Description TODO
 * @Author钰玟
 * @Date2025/2/15 下午3:10
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    /**
     * 微信登录
     * @param userLoginDTO 用户登录信息
     * @return 用户信息
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获取openid
        String openid = getOpenid(userLoginDTO);

        // 判断openid是否为空
        if(openid==null || openid.equals("")){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 查询数据库
        User user = userMapper.getByOpenId(openid);
        //判断openId是否为空，如果不为空即是 登录直接返回
        //为空即是 新用户 直接插入数据库
        if(user==null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();

            userMapper.insert(user);
        }


        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        // 封装请求参数
        HashMap <String, String> paramMap = new HashMap <>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        // 发起请求
        String string = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
        // 解析响应结果
        JSONObject jsonObject = JSONObject.parseObject(string);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
